import Vue from 'vue'
import Vuex from 'vuex'
import api from '@/api'
import cache from '@/utils/cache'
import { generateImgUrl } from '@/utils'
import dealHomeNav from '@/utils/dealHomeNav'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    userInfo: {},
    isLogin: false,
    roles: [],
    mpImgs: {},
    wechatConfig: {},
    homeNav: [],
    tabBarParams: {},
    needAdviceRefreshTime: null,
  },
  mutations: {
    SET_MPIMGS (state, value) {
      state.mpImgs = value
    },
    SET_HOME_NAV (state, value) {
      state.homeNav = value
    },
    SET_USERINFO (state, value) {
      state.userInfo = value
    },
    SET_ISLOGIN (state, value) {
      state.isLogin = value
    },
    SET_ROLES (state, value) {
      state.roles = value
    },
    SET_WECHAT_CONFIG (state, value) {
      state.wechatConfig = value
    },
    SET_TAB_BAR_PARAMS (state, value) {
      state.tabBarParams = value
    },
    SET_NEED_ADVICE_REFRESH_TIME (state, value) {
      state.needAdviceRefreshTime = value
    },
  },
  actions: {
    async initMpImages (context) {
      context.commit('SET_MPIMGS', cache.mpImgs.get() || {})
      const { result } = await api.getDict({ type: 'mp_icon' })
      const map = {}
      result.forEach(item => {
        map[item.name] = generateImgUrl(item.icon)
      })
      context.commit('SET_MPIMGS', map)
      cache.mpImgs.set(map)
    },
    async initWechatConfig (context) {
      const { result } = await api.getDict({ type: 'wechat_config' })
      const map = {}
      result.forEach(item => {
        map[item.name] = item.value
      })
      context.commit('SET_WECHAT_CONFIG', map)
      console.log(map)
    },
    initByLocalStore (context) {
      try {
        {
          const result = cache.homeApiResult.get()
          if (result) {
            context.commit('SET_USERINFO', result)
            context.commit('SET_ISLOGIN', true)
          }
        }
        {
          const result = cache.homeNav.get()
          if (result) {
            context.commit('SET_HOME_NAV', result)
          }
        }
      } catch (e) {

      }
    },
    async init (context) {
      try {
        const { result } = await api.getDict({ type: 'home_config' })
        const dealResult = dealHomeNav(result)
        context.commit('SET_HOME_NAV', dealResult)
        cache.homeNav.set(dealResult)

        if (cache.Authorization.get()) {
          const { result } = await api.home()
          if (result) {
            context.commit('SET_USERINFO', result)
            context.commit('SET_ISLOGIN', true)
            cache.homeApiResult.set(result)
          } else {
            context.commit('SET_ISLOGIN', false)
          }
        } else {
          context.commit('SET_ISLOGIN', false)
        }
      } catch (e) {
        context.commit('SET_ISLOGIN', false)
      }
    },
    async getRoles (context) {
      const { result } = await api.getRoles()
      context.commit('SET_ROLES', result)
    },
  },
})
